//
//  ZLBaseViewController.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/15.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import UIKit

//class ZLBaseViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//swift 利用extension可以吧函数功能分类管理 便于阅读和维护
//1. extension中不能有属相
//2.不能重写父类的方法 是子类的职责
class ZLBaseViewController: UIViewController {

    
    var visitorInfoDictionary: [String: String]?
    //如果用户没有登录就不创建
    var tableView: UITableView?
    
    var refreshControl: ZLRefreshControl?
    //用来区分上拉刷新标记
    var isPullup = false
    
    /// 自定义导航条
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.hm_screenWidth(), height: 64))
    /// 自定义导航条目录
    lazy var navItem = UINavigationItem();
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        setupUI()
        ZLNetWorkManager.shared.userLogon ? loadData() : ()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(longinSuccess), name: NSNotification.Name(rawValue: ZLUserLonginSuccessNotification), object: nil)
    }

    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    func loadData() -> () {
        
        //由子类负责实现
        //如果子类不实现任何方法默认关闭刷新控件
        self.refreshControl?.endRefreshing()
        
    }
    override var title: String?{
        
        didSet {
            
            navItem.title = title;
        }
    }
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    

}
//MARK --访客视图监听方法
extension ZLBaseViewController{
    
    @objc fileprivate func longinSuccess(n: Notification){
        
        
        print("登录成功")
        //登录前左边是注册右边是登录
        navItem.rightBarButtonItem = nil
        navItem.leftBarButtonItem = nil
        //更新UI 访客视图 替换成  表格视图
        //需要重新执行View
        //在访问View的gettter是 如果View为nil 会执行loadView
        view = nil
        
        NotificationCenter.default.removeObserver(self)
    }
    @objc fileprivate func login(){
        
        print("用户登录")
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(ZLUersShouldLoginNotigication), object: nil)
        
        
    }
    @objc fileprivate func register(){
        
        print("用户注册")
        
    }
    @objc fileprivate func towatchOthers(){
        
        print("去关注")
        
    }
    
}
// MARK: ---- 设置界面
extension ZLBaseViewController {
    
    fileprivate func setupUI() {
        
        view.backgroundColor = UIColor.white
        
        automaticallyAdjustsScrollViewInsets = false;
        setNaviHationBar()
        
        //查看用户是否登录
        
        ZLNetWorkManager.shared.userLogon ? setupTableView() : setupVisitorView()
        
    }
    fileprivate func setupVisitorView(){
        
        let visitorView = ZLVisitorsView(frame: view.bounds)
        
        
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        visitorView.visitorInfo = visitorInfoDictionary
        
        //添加访客视图按钮的监方法
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        if tabBarController?.selectedIndex == 0
        {
            //设置导航栏按钮
            navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
            navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
            
            visitorView.toWatchOther.addTarget(self, action: #selector(towatchOthers), for: .touchUpInside)
        }
        if tabBarController?.selectedIndex == 3
        {
            //设置导航栏按钮
            navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
            navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
            
        }
        
        
        
        print("\(visitorView)")
    }
    func setupTableView(){
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        //子类直接实现数据源方法
        tableView?.delegate = self
        tableView?.dataSource = self;
        
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        //修改指示器缩进 强行解包是为了拿到一个必有的contentInset
        tableView?.scrollIndicatorInsets = (tableView?.contentInset)!
        
        //刷新控件
        refreshControl = ZLRefreshControl()
        
        
        tableView?.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    fileprivate func setNaviHationBar(){
        
        
        //添加导航条
        view.addSubview(navigationBar)
        //item设置给bar
        navigationBar.items = [navItem]
        //设置bar的渲染颜色
        navigationBar.barTintColor = UIColor.hm_color(withHex: 0xF6F6F6)
        
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        ///设置系统按钮的文字渲染颜色
        navigationBar.tintColor = UIColor.orange
        
        
        
    }
    
}
extension ZLBaseViewController: UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 0
    }
    //积累准备方法  之类负责实现
    //子类的数据源方法不需要super
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        return UITableViewCell()
    }
    //在显示最后一行的时候做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let row = indexPath.row
        
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0
        {
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        //最后一行 同时没有开始上拉刷新
        if row == (count - 1) && !isPullup
        {
            print("上拉刷新")
            
            isPullup = true
            //开始刷新
            loadData()
        }
        
    }
    
}
